
var gl;
var points;

function clone(myObj) {
    if (typeof(myObj) != 'object' || myObj == null) return myObj;
    var newObj = new Object();
    for (var i in myObj) {
        newObj[i] = clone(myObj[i]);
    }
    return newObj;
}

function triangle(lst, a, b, c) {
    lst.push(a);
    lst.push(b);
    lst.push(c);
}

function subdivision(a, b, c, count) {
    var mid_ab = mix(a, b, 0.5);
    var mid_ac = mix(c, a, 0.5);
    var mid_bc = mix(b, c, 0.5);
    var lst = [];

    if (count > 1) {
        count -= 1;
        lst.concat(subdivision(a, mid_ab, mid_ac, count));
        lst.concat(subdivision(mid_ab, b, mid_bc, count));
        lst.concat(subdivision(mid_ac, mid_bc, c, count));
    } else {
        triangle(lst, mid_ab, b, mid_bc);
        triangle(lst, a, mid_ab, mid_ac);
        triangle(lst, mid_ac, mid_bc, c);
    }
    return lst;
}

window.onload = function init()
{
    var canvas = document.getElementById("gl-canvas");
    gl = WebGLUtils.setupWebGL( canvas );
    if ( !gl ) { alert("WEBGL 不可用！"); }

    var vertices_init = [
        vec2(   0,  0.25),
        vec2( 0.5,  -0.5),
        vec2(-0.5,  -0.5)
    ];
    
    var vertices = subdivision(
        vertices_init[0], vertices_init[1], vertices_init[2],
        1
    );

    // Configure WebGL
    gl.viewport( 0, 0, canvas.width, canvas.height );
    gl.clearColor( 1.0, 1.0, 1.0, 1.0 );

    // 加载 shaders 和初始化属性buffer

    var program = initShaders( gl, "vertex-shader", "fragment-shader" );
    gl.useProgram( program );
    
    console.log(vertices);

    // 把数据加载进GPU
    var bufferId = gl.createBuffer();
    gl.bindBuffer( gl.ARRAY_BUFFER, bufferId );
    gl.bufferData( gl.ARRAY_BUFFER, flatten(vertices), gl.STATIC_DRAW );


    // 将shader变量与数据buffer关联    
    var vPosition = gl.getAttribLocation( program, "vPosition" );
    gl.vertexAttribPointer( vPosition, 2, gl.FLOAT, false, 0, 0 );
    gl.enableVertexAttribArray( vPosition );

    render(vertices.length);
};


function render(len)
{
    gl.clear( gl.COLOR_BUFFER_BIT );
    gl.drawArrays( gl.LINE_LOOP, 0, len );
}
